<template>
  <div class="echart-property-popup">
    <div class="rooter">
      <el-button
        icon="Tools"
        :link="true"
        type="primary"
        @click="openDialog()"
      >
        {{ $demoi18n('panel.adapt.AdaptiveSettings') }}
      </el-button>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="$demoi18n('panel.adapt.AdaptiveSettings')"
      :width="width"
      append-to-body
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :class="`${customClass} dynamic-adaptation-popup ${visualThemeClassName} ${xvueNameSpace}`"
    >
      <div class="cont">
        <el-form
          ref="adaptSettingForm"
          :model="form_"
        >
          <div class="block">
            <el-row>
              <el-col :span="12">
                <div class="grid-content">
                  <VsFormItem
                    v-if="dynOptions.includes('minWidth')"
                    :label="`${unitName}${$demoi18n('panel.adapt.minWidth')}`"
                  >
                    <Range
                      v-model:value="form_.adaptSetting.minWidth"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content">
                  <VsFormItem
                    v-if="dynOptions.includes('maxWidth')"
                    :label="`${unitName}${$demoi18n('panel.adapt.maxWidth')}`"
                  >
                    <Range
                      v-model:value="form_.adaptSetting.maxWidth"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <div class="grid-content">
                  <VsFormItem
                    v-if="dynOptions.includes('minHeight')"
                    :label="`${unitName}${$demoi18n('panel.adapt.minHeight')}`"
                  >
                    <Range
                      v-model:value="form_.adaptSetting.minHeight"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content">
                  <VsFormItem
                    v-if="dynOptions.includes('maxHeight')"
                    :label="`${unitName}${$demoi18n('panel.adapt.maxHeight')}`"
                  >
                    <Range
                      v-model:value="form_.adaptSetting.maxHeight"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <div class="grid-content">
                  <VsFormItem
                    v-if="dynOptions.includes('paddingLeft')"
                    :label="`${unitName}${$demoi18n('panel.adapt.leftMargin')}`"
                  >
                    <Range
                      v-model:value="form_.adaptSetting.paddingLeft"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content">
                  <VsFormItem
                    v-if="dynOptions.includes('paddingRight')"
                    :label="`${unitName}${$demoi18n('panel.adapt.rightMargin')}`"
                  >
                    <Range
                      v-model:value="form_.adaptSetting.paddingRight"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
            </el-row>
            <VsFormItem
              v-if="dynOptions.includes('unitGapRate')"
              :label="$demoi18n('panel.adapt.valSpacing')"
            >
              <Range
                v-model:value="form_.adaptSetting.unitGapRate"
                :min="0"
                :max="100"
                type="input"
              />
            </VsFormItem>
            <VsFormItem
              v-if="dynOptions.includes('settingType')"
              :label="$demoi18n('panel.adapt.adaptMode')"
            >
              <el-select
                v-model="form_.adaptSetting.type"
                size="default"
              >
                <el-option
                  v-for="(item, index) in settingOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </VsFormItem>
            <el-row>
              <el-col
                v-if="String(form_.adaptSetting.type) === '1' && showHeightAdjustOption"
                :span="12"
              >
                <div class="grid-content">
                  <VsFormItem :label="$demoi18n('panel.adapt.setWidth')">
                    <Range
                      v-model:value="form_.adaptSetting.columnAdjustWidth"
                      :min="0"
                      :max="1000"
                      type="input"
                    />
                  </VsFormItem>
                </div>
              </el-col>
            </el-row>
            <div
              v-if="['1', '2', '3'].includes(form_.adaptSetting.type)"
              class="table-container"
            >
              <div
                v-if="
                  String(form_.adaptSetting.type) === '2' && config.propertyPannelName !== `config_${xvueNameSpace_}multi_value`
                "
                class="info-wrap set-line-height-item"
              >
                <VsFormItem class="line-gap-item">
                  <span :style="{ 'min-width': '153px', color: xvueTheme === 'dark' ? '#e0e0e0' : '#606266' }">
                    {{ $demoi18n('panel.adapt.setRowHeight') }}
                    <br />
                    <span v-if="form.typeSetting === 'horizontal'">{{ $demoi18n('panel.adapt.unitTextHeight') }}</span>
                  </span>
                  <el-input
                    v-model="form_.adaptSetting.lineGap"
                    :placeholder="$demoi18n('panel.adapt.setUnitTextHeight')"
                  ></el-input>
                </VsFormItem>
              </div>
              <div
                v-if="['3'].includes(form_.adaptSetting.type)"
                class="info-wrap set-line-height-item2"
              >
                <p
                  v-if="['3'].includes(form_.adaptSetting.type) && form.typeSetting !== 'horizontal'"
                  class="info-blue"
                >{{ $demoi18n('panel.adapt.verticalTable') }}</p>
                <p
                  v-if="['3'].includes(form_.adaptSetting.type) && form.typeSetting === 'horizontal'"
                  class="info-blue"
                >{{ $demoi18n('panel.adapt.horizontalTable') }}</p>
                <VsFormItem class="line-gap-item">
                  <p><span :style="{ color: xvueTheme === 'dark' ? '#e0e0e0' : '#606266' }">{{
                    $demoi18n('panel.adapt.setRowHeight')
                  }}</span></p>
                  <el-input v-model="form_.adaptSetting.lineGap"></el-input>
                </VsFormItem>
              </div>

              <el-table
                v-if="
                  ['1', '3'].includes(form_.adaptSetting.type) &&
                    config.propertyPannelName !== `config_${xvueNameSpace_}multi_value`
                "
                :data="form_.adaptSetting.tableData"
                border
                style="width: 100%"
                :class="`${xvueTheme}`"
                max-height="500"
              >
                <el-table-column
                  fixed
                  prop="id"
                  :label="$demoi18n('panel.th.number')"
                  width="60"
                > </el-table-column>
                <el-table-column
                  :render-header="renderTableHeader"
                  prop="name"
                  :label="form.typeSetting === 'horizontal' ? $demoi18n('panel.th.columnId') : $demoi18n('panel.th.fieldName')"
                >
                  <template #default="scope">
                    <VsFormItem>
                      <el-select
                        v-model="scope.row.name"
                        :placeholder="$demoi18n('view.select.placeholder')"
                      >
                        <el-option
                          v-for="(item, index) in restColumnOptions"
                          :key="item.value + index"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </VsFormItem>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="form.typeSetting === 'vertical'"
                  :render-header="renderTableHeader"
                  prop="width"
                  :label="`${$demoi18n('panel.adapt.columnWidth')}（px）`"
                >
                  <template #default="scope">
                    <VsFormItem>
                      <el-input v-model="scope.row.width"></el-input>
                    </VsFormItem>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="form.typeSetting === 'horizontal'"
                  :render-header="renderTableHeader"
                  prop="width"
                  :label="`${$demoi18n('panel.adapt.columnWidth')}（px）`"
                >
                  <template #default="scope">
                    <VsFormItem>
                      <el-input v-model="scope.row.width"></el-input>
                    </VsFormItem>
                  </template>
                </el-table-column>
                <el-table-column
                  :render-header="renderTableHeader"
                  fixed="right"
                  :label="$demoi18n('echart.th.operation')"
                >
                  <template #default="scope">
                    <el-button
                      :link="true"
                      type="primary"
                      size="small"
                      @click="deleteRow(scope)"
                    >{{
                      $demoi18n('panel.button.delete')
                    }}</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div
                v-if="
                  disableAdd &&
                    ['1', '3'].includes(form_.adaptSetting.type) &&
                    config.propertyPannelName !== `config_${xvueNameSpace_}multi_value`
                "
                class="info-wrap add-wrap"
              >
                <p class="info-blue">
                  <el-button
                    type="primary"
                    icon="CirclePlus"
                    plain
                    @click="addRow()"
                  >{{
                    $demoi18n('btn.add')
                  }}</el-button>
                  {{ $demoi18n('panel.adapt.restAdaptive') }}
                </p>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span>
          <el-button
            size="small"
            @click="cancelForm()"
          >{{ $demoi18n('btn.cancel') }}</el-button>
          <el-button
            type="primary"
            size="small"
            @click="submitForm()"
          >
            {{ $demoi18n('btn.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang='jsx'>
import EchartCommonMixin from '@/components/common/echart/mixins/echart-common-mixin.js';
import Range from '../../common/range/range.vue';
import { $demoi18n } from '@/utils/lang';

export default {
  components: {
    Range,
  },
  mixins: [EchartCommonMixin],
  props: {
    form: Object,
    config: Object,
    width: {
      type: String,
      default: '780px',
    },
    unitName: {
      type: String,
      default: $demoi18n('word.singleValue'),
    },
    showHeightAdjustOption: Boolean,
    showWidthAdjustOption: Boolean,
    dynOptions: Array,
    settingOptions: Array,
    widgetInstanceId: String,
  },
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      xvueNameSpace_: process.env.xvueNameSpace_,
      xvueTheme: window._adoPremise.uc.theme,
      fits: [],
      dialogVisible: false,
      form_: {},
      comps: {},
      curInfo: {}, // 子组件一些操作状态记录到这里
      tableBlade: {
        id: 1,
        name: '',
        type: '',
        width: '',
        dot: true,
      },
    };
  },
  computed: {
    customClass() {
      const arr = [
        'echart-property-popup_dialog',
        `echart-property-popup_dialog_${window._adoPremise.uc.theme || 'light'}`,
      ];
      return arr.join(' ');
    },
    disableAdd() {
      if (['1', '3'].includes(this.form_.adaptSetting.type)) {
        return this.form_.adaptSetting.tableData.length < this.columnOptions.length;
      } else {
        return false;
      }
    },
    restColumnOptions() {
      const ret = this.getDiffVal(this.columnOptions, this.form_.adaptSetting.tableData, 'value', 'name');
      return ret;
    },
    columnOptions() {
      const { tableData } = this.config.config.data;
      const arr = [];
      let obj = {};
      if (this.form.typeSetting === 'horizontal') {
        if (this.form.hasColumnHeader) {
          obj = {
            label: this.$demoi18n('panel.label.tableHeader'),
            value: this.$demoi18n('panel.label.tableHeader'),
          };
          arr.push(obj);
        }
        const pageTable = document.getElementById(`chartMain${this.widgetInstanceId}`);
        const arrLen = pageTable.getElementsByClassName('vxe-body--row')[0].getElementsByTagName('td').length;
        if (arrLen) {
          for (let i = 0; i < arrLen - 1; i++) {
            obj = {
              label: i + 1,
              value: i + 1,
            };
            arr.push(obj);
          }
        }
        return arr;
      }
      if (this.form.columnWidth) {
        return this.getHeaderList(this.form.columnWidth);
      }
      tableData.map(item => {
        obj = {
          label: item.field,
          value: item.field,
        };
        arr.push(obj);
      });
      return arr;
    },
  },
  watch: {
    'form.typeSetting': {
      handler(oldVal, newVal) {
        if (oldVal !== newVal) {
          this.form.adaptSetting.tableData = [];
          this.form_.adaptSetting.tableData = [];
          this.form.adaptSetting.type = '0';
          this.form_.adaptSetting.type = '0';
        }
      },
    },
  },
  created() {
    this.syncForm(this.form, this.form_);
  },
  methods: {
    getHeaderList(columnWidth) {
      const arr = [];
      if (columnWidth[0].name) {
        arr.push({
          label: columnWidth[0].name,
          value: columnWidth[0].name,
        });
      }
      const crosstab = document.getElementById(`chartMain${this.widgetInstanceId}`);
      const tableHeader = crosstab.getElementsByClassName('vxe-header--row')[0].getElementsByTagName('th');
      if (tableHeader) {
        const tableIndex = columnWidth[0].name ? 1 : 0;
        for (let i = tableIndex; i < tableHeader.length; i++) {
          arr.push({
            label: tableHeader[i].innerText,
            value: tableHeader[i].innerText,
          });
        }
      }
      return arr;
    },
    getDiffVal(arr1, arr2, key1, key2) {
      const retArr = [];
      arr1.map(item => {
        const child = arr2.filter(n => n[key2] === item[key1]);
        child.length === 0 ? retArr.push(item) : null;
      });
      return retArr;
    },
    deleteRow(scoped) {
      this.form_.adaptSetting.tableData.splice(scoped.$index, 1);
    },
    addRow() {
      if (this.form_.adaptSetting.tableData.length >= this.columnOptions.length) {
        return;
      }
      this.tableBlade.id = this.form_.adaptSetting.tableData.length + 1;
      this.form_.adaptSetting.tableData.push(JSON.parse(JSON.stringify(this.tableBlade)));
    },
    syncForm(srcForm, tarForm) {
      if (srcForm === this.form) {
        this.form_ = JSON.parse(JSON.stringify(this.form));
      } else {
        this.form.adaptSetting = this.form_.adaptSetting;
      }
    },
    openDialog() {
      this.syncForm(this.form, this.form_);
      this.dialogVisible = true;
    },
    submitForm() {
      this.syncForm(this.form_, this.form);
      this.dialogVisible = false;
    },
    cancelForm() {
      this.dialogVisible = false;
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
  },
};
</script>
<style lang="less" scoped>
.echart-property-popup {
  display: inline-block;
  .rooter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      width: 78px;
      text-align: right;
      padding-right: 12px;
      display: inline-block;
    }
    :deep(.el-button) {
      width: 100%;
      flex: 1;
      text-align: left;
    }
  }
}
:deep(.el-radio-group) {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
:deep(.el-radio-button__inner) {
  border: none;
}
:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: none;
}
:deep(.el-avatar) {
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: auto;
    height: auto;
    max-height: 100%;
    max-width: 100%;
  }
}
:deep(.el-avatar.dark) {
  background-color: rgb(13, 38, 58);
}
:deep(.el-avatar.light) {
  background-color: #fff;
}
</style>

<style lang="less">
.dynamic-adaptation-popup {
  .el-form-item {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
  }
  .el-form-item__label {
    width: max-content !important;
    min-width: 153px;
    text-align: left;
  }
  .el-form-item__content {
    width: 220px;
    margin-left: 0;
  }
  p {
    margin: 0;
    line-height: 1.6;
    width: 350px;
  }
  .info-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .line-gap-item {
    .el-form-item__label {
      text-align: right;
      color: #409eff;
    }
  }
  .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  .el-table td,
  .el-table th {
    padding: 5px 0;
  }
  .el-table.dark {
    border-color: #0e2b40;
    background-color: #0d2030;
    .el-table__header,
    .el-table__body {
      background-color: #071f30;
      th,
      td {
        border-color: #0e2b40;
        background-color: #071f30;
      }
    }
    .el-table__fixed-right::before,
    .el-table__fixed::before {
      background-color: #0e2b40;
    }
    .el-table__fixed-right-patch {
      background-color: #071f30;
      border-color: #071f30;
    }
  }
  .el-table.dark::before,
  .el-table--border.dark::after,
  .el-table--group.dark::after {
    background-color: #0e2b40;
  }
  .is-plain {
    padding: 5px 10px;
    margin-right: 10px;
  }
  .add-wrap {
    margin-top: 5px;
  }
  .cell {
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    white-space: nowrap !important;
  }
  .danger {
    color: #f56c6c;
  }
  .info-blue {
    color: #409eff;
    word-break: break-word;
  }
}
.set-line-height-item {
  width: 50%;
  :deep(.el-form-item__content) {
    width: 100%;
    display: flex;
    align-content: flex-end;
    align-items: flex-end;
    p {
      margin-right: 15px;
      span {
        color: rgb(40, 144, 191);
      }
    }
    :deep(.el-input) {
      width: 115px;
    }
  }
}
.set-line-height-item2 {
  :deep(.el-form-item__content) {
    display: flex;
    width: 50%;
    justify-content: flex-end;
  }
  :deep(.line-gap-item) {
    display: flex;
    width: 100%;
    justify-content: flex-end;
    .el-form-item__content {
      width: 50%;
    }
    p {
      width: 220px;
      margin-right: 12px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
</style>
